<?php
/**
 * Created by PhpStorm.
 * User: Sunqj
 * Date: 2017/1/19
 * Time: 下午8:21
 */

namespace app\admin\controller;

use think\Exception;
use think\Db;
use app\common\model\Message;

class Brand extends Common
{
    public function index()
    {
        //设置标题
        $this->templateTitle("品牌管理");
        $where['is_valid'] = 1;
        $id = trim(input('id'));
        $this->assign('id', $id);
        if ($id) {
            $where['id'] = $id;
        }

        $title = trim(input('title'));
        $this->assign('title', $title);
        if ($title) {
            $where['title'] = ['like', '%' . $title . '%'];
        }
        //获取所有用户
        $list = Db::name("brand")
            ->where($where)
            ->order("display_order DESC, id DESC")
            ->paginate(10);
        $this->assign("page", $list->render());
        $list1 = $list->toArray()['data'];
        foreach ($list1 as &$l){
            $cid = Db::name("category_brand")->where("brand_id", $l['id'])->column("category_id1");
            if(!empty($cid)){
                $l['cate_list'] = Db::name("category")->whereIn("id", $cid)->column("title");
            }else{
                $l['cate_list'] = [];
            }
        }
        $this->assign("list", $list1);
        return $this->fetch();
    }

    //添加
    public function add()
    {

        if (request()->isGet()) {
            $this->layoutModal();
            $this->templateTitle('添加品牌');
            $this->assign('category_list', $this->get_category(1));
            return $this->fetch();
        }

        if (request()->isAjax()) {
            //创建数据
            $data = array(
                "create_time" => now_datetime(),
                "update_time" => now_datetime()
            );

            $data['title'] = request()->param("title");
            if (empty($data['title'])) {
                return $this->ajaxError('请输入品牌名称');
            }
            $map = [
                'title' => $data['title']
            ];
            $exist = Db::name('brand')->where($map)->find();
            if ($exist) {
                return $this->ajaxError('品牌【' . $data['title'] . '】已存在');
            }
            //幻灯图片
            $data["img_url"] = request()->param("img_url");
            $data["brand_type"] = input("brand_type");

            if(empty($data['img_url'])){
                return $this->ajaxError('请上传幻灯图片');
            }

            $data["description"] = trim(request()->param("description"));

            //排序
            $data["display_order"] = request()->param("display_order");
            //是否显示
            $data["is_visible"] = request()->param("visible");
            try {
                $brand_id = Db::name('brand')
                    ->insertGetId($data);

                $category_id1 = @$_POST['category_id1'];
                if (is_array($category_id1) && count($category_id1) > 0) {
                    $arr = [];
                    foreach ($category_id1 as $key => $item) {
                        $arr[$key]['brand_id'] = $brand_id;
                        $arr[$key]['category_id1'] = $item;
                    }
                    Db::name('category_brand')->insertAll($arr);
                }
                /*操作记录*/
                Message::admin_log(0, "后台添加品牌");
                return $this->ajaxSuccess("添加成功！");
            } catch (Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                return $this->ajaxError($exception->getMessage());
            }
        }
    }

    //编辑
    public function edit()
    {
        //ID
        $Id = request()->param("id");

        if (request()->isGet()) {
            $this->layoutModal();
            //获取信息
            $info = Db::name("brand")
                ->where("id", $Id)
                ->find();
            $this->assign("info", $info);
            $this->assign("single_image", array("img_url" => $info["img_url"]));
            $this->assign('category_list', $this->get_category(2, $Id));

            return $this->fetch();
        }

        if (request()->isAjax()) {
            //
            //创建数据
            $data = array(
                "update_time" => now_datetime(),
            );
            $data['title'] = request()->param("title");
            if (empty($data['title'])) {
                return $this->ajaxError('请输入品牌名称');
            }
            $map = [
                'title' => $data['title'],
                'id' => ['neq', $Id]
            ];
            $exist = Db::name('brand')->where($map)->find();
            if ($exist) {
                return $this->ajaxError('品牌【' . $data['title'] . '】已存在');
            }
            $data["description"] = trim(request()->param("description"));
            //排序
            $data["display_order"] = request()->param("display_order");
            //是否显示
            $data["is_visible"] = request()->param("visible");

            //幻灯图片
            $data["img_url"] = request()->param("img_url");

            $data["brand_type"] = input("brand_type");
            if(empty($data['img_url'])){
                return $this->ajaxError('请上传幻灯图片');
            }
            try {
                //更新分类ID路径
                Db::name("brand")
                    ->where("id", $Id)
                    ->update($data);
                Db::name('category_brand')
                    ->where('brand_id', $Id)
                    ->delete();

                $category_id1 = @$_POST['category_id1'];
                if (is_array($category_id1) && count($category_id1) > 0) {
                    $arr = [];
                    foreach ($category_id1 as $key => $item) {
                        $arr[$key]['brand_id'] = $Id;
                        $arr[$key]['category_id1'] = $item;
                    }
                    Db::name('category_brand')->insertAll($arr);
                }
                /*操作记录*/
                Message::admin_log(0, "后台编辑品牌");
                return $this->ajaxSuccess("编辑成功！");
            } catch (Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                return $this->ajaxError($exception->getMessage());
            }
        }
    }

    //删除
    public function remove()
    {
        if (request()->isAjax()) {
            //获取ID
            $Id = request()->param("id");
            // 删除
            try {
                $result = Db::name('brand')
                    ->where('id', $Id)
                    ->update(['is_valid' => 0, 'update_time' => now_datetime()]);
                /*操作记录*/
                Message::admin_log(0, "后台删除品牌");
                return $this->ajaxSuccess("删除成功！");
            } catch (Exception $exception) {
                return $this->ajaxError($exception->getMessage());
            }
        }
    }

    //更改菜单显示隐藏
    public function visible()
    {
        if (request()->isAjax()) {
            //菜单ID
            $id = request()->param("id");
            //获取可见性状态
            $status = request()->param("status");

            try {
                //修改菜单显示隐藏
                $save = Db::name("brand")
                    ->where("id", $id)
                    ->setField("is_visible", $status);

                if ($save) {
                    /*操作记录*/
                    Message::admin_log(0, "后台修改品牌的状态");
                    return $this->ajaxSuccess("设置品牌显示或隐藏成功！");
                } else {
                    return $this->ajaxError("设置品牌显示或隐藏失败！");
                }
            } catch (Exception $exception) {
                return $this->ajaxError($exception->getMessage());
            }
        }
    }

    //还原
    public function reduction()
    {
        if (request()->isAjax()) {
            //获取品牌ID
            $brandId = request()->param("id");

            try {
                Db::name("brand")
                    ->where("id", $brandId)
                    ->setField("is_valid", 1);
                /*操作记录*/
                Message::admin_log(0, "后台还原品牌:" . $brandId);
                return $this->ajaxSuccess("还原品牌成功！");
            } catch (Exception $exception) {
                return $this->ajaxError("还原品牌失败！");
            }
        }
    }

    //彻底删除
    public function deletes()
    {
        if (request()->isAjax()) {
            //获取品牌ID
            $brandId = request()->param("id");

            try {
                Db::name("brand")
                    ->where("id", $brandId)
                    ->delete();
                Db::name('category_brand')->where('brand_id', $brandId)->delete();
                /*操作记录*/
                Message::admin_log(0, "后台删除品牌");
                return $this->ajaxSuccess("彻底删除品牌成功！");
            } catch (Exception $exception) {
                global $admin_has_exception;
                $admin_has_exception = true;
                return $this->ajaxError($exception->getMessage());
            }
        }
    }

    public function recycle()
    {
        if (request()->isGet()) {
            //设置标题
            $this->templateTitle("品牌回收站");

            //获取所有用户
            $list = Db::name("brand")
                ->where('is_valid', 'neq', 1)
                ->paginate(15);

            $this->assign("list", $list);

            return $this->fetch();
        }
    }

    //获取
    private function get_category($type = 1, $brand_id = '')
    {
        if ($type == 1) {
            $where = [
                'level' => 1,
                'is_valid' => 1
            ];
            $list = Db::name('category')->where($where)->order('display_order DESC,id DESC')->field('id,title,is_visible')->select();
        } else {
            $list = Db::name('category')
                ->alias('ca')
                ->join('__CATEGORY_BRAND__ cb', 'cb.brand_id=' . $brand_id . ' AND cb.category_id1=ca.id', 'LEFT')
                ->where('ca.level=1 AND ca.is_valid=1')
                ->order('ca.display_order DESC,ca.id DESC')
                ->field('ca.id,ca.title,ca.is_visible,cb.id as cbid')
                ->select();
        }
        return $list;
    }
}